/**
 * 题目管理模块用到的js代码
 */

//删除按钮的监听方法
function removeConfirm(){
	var row = $('#dg').datagrid('getSelected');
    if (row){
    	$.messager.confirm('信息提示', '确认要删除吗?', function(r){
            if (r){
            	$.get(contextPath+"/question/delete.do?id="+row.id,null,
					function(data,state){
						if(data.status==1){
							$.messager.alert('信息提示','删除成功');
							$('#dg').datagrid('reload');//刷新
						}else{
							$.messager.alert('信息提示','删除失败');
						}
					}
				);
            	 
            }
        });
        
    }else{
    	$.messager.alert('信息提示','请选择一条数据进行删除');
    }
    
}

//修改按钮的监听方法，加载准备要修改的数据
function loadRemote(){
	var row = $('#dg').datagrid('getSelected');
    if (row){
        $('#editForm').form('load', contextPath+'/question/update.do?id='+row.id);
		if(row.question){
			$("#edit_status").combobox('select', row.status);
		}
        
        $('#edit').dialog('open');
    }else{
    	$.messager.alert('信息提示','请选择一条数据进行修改');
    }
}

//添加对话框中的保存按钮的监听方法
$(function(){//保存添加
	$("#add-save-button").click(
		function(){
			var datas=$("#addForm").serialize();//表单数据项
			$.messager.confirm('信息提示', '确认要保存吗?', function(r){
   	            if (r){
   	            	$.post(contextPath+"/question/addSave.do",datas,
						function(data,state){
							if(data.status==1){
								$.messager.alert('信息提示','保存成功');
								$('#addForm').form('clear');//清空表单数据
								$('#dg').datagrid('reload');//刷新
								$('#add').dialog('close');
							}else{
								$.messager.alert('信息提示','保存失败');
							}
						}
					);
   	            }
   	        });
		}	

	)
}); 	

//修改对话框中的保存按钮的监听方法     
$(function(){//保存修改
	$("#edit-save-button").click(
		function(){
			var datas=$("#editForm").serialize();//表单数据项
			$.messager.confirm('信息提示', '确认要保存吗?', function(r){
   	            if (r){
   	            	$.post(contextPath+"/question/updateSave.do",datas,
						function(data,state){
							if(data.status==1){
								$.messager.alert('信息提示','保存成功');
								$('#editForm').form('clear');//清空表单数据
								$('#dg').datagrid('reload');//刷新
								$('#edit').dialog('close');
							}else{
								$.messager.alert('信息提示','保存失败');
							}
						}
					);
   	            }
   	        });
		}	

	)
});


//查询对话框中查询按钮监听方法
$(function(){//查询
	$("#search-save-button").click(
		function(){
			var datas=$("#searchForm").serializeArray();//表单数据项
			var serializeObj={};
            $(datas).each(function(){
                if(serializeObj[this.name]){
                    if($.isArray(serializeObj[this.name])){
                        serializeObj[this.name].push(this.value);
                    }else{  
                        serializeObj[this.name]=[serializeObj[this.name],this.value];
                    }
                }else{
                    serializeObj[this.name]=this.value;
                }
            });
			$('#dg').datagrid('reload',serializeObj);//查询刷新
			$('#search').dialog('close');
		}

	)
});

//表格数据翻页栏设置
$(function(){

    $('#dg').datagrid({
    	columns:[[
			{field:'id',title:'编号', width:60},
    		{field:'db_id',title:'题库编号', width:60,
    			formatter: function(value,row,index){
    				if (row.questionDb){
    					return row.questionDb.id;
    				} else {
    					return value;
    				}
    			}
    		},
    		{field:'db_name',title:'题库名称', width:160,
    			formatter: function(value,row,index){
    				if (row.questionDb){
    					return row.questionDb.name;
    				} else {
    					return value;
    				}
    			}
    		},
    		{field:'admin_id',title:'管理员编号', width:70,
    			formatter: function(value,row,index){
    				if (row.admin){
    					return row.admin.id;
    				} else {
    					return value;
    				}
    			}
    		},
    		{field:'admin_name',title:'管理员', width:100,
    			formatter: function(value,row,index){
    				if (row.admin){
    					return row.admin.user_name;
    				} else {
    					return value;
    				}
    			}
    		},
    		{field:'qtype',title:'题目类型', width:60,
    			formatter: function(value,row,index){
    				if (row.qtype){//1单选，2多选，3填空，4判断，5问答
    					switch (row.qtype){
	    					case 1:
	    						return "单选";
	    						break;
	    					case 2:
	    						return "多选";
	    						break;
	    					case 3:
	    						return "填空";
	    						break;
	    					case 4:
	    						return "判断";
	    						break;
	    					case 5:
	    						return "问答";
	    						break;
    					}
    				} else {
    					return value;
    				}
    			}
    		},
    		{field:'qlevel',title:'难度级别', width:60,
    			formatter: function(value,row,index){
    				if (row.qlevel){//1易，2正常，3难
    					switch (row.qlevel){
	    					case 1:
	    						return "易";
	    						break;
	    					case 2:
	    						return "正常";
	    						break;
	    					case 3:
	    						return "难";
	    						break;
    					}
    				} else {
    					return value;
    				}
    			}
    		},
    		{field:'status',title:'状态', width:70,
    			formatter: function(value,row,index){
    				if (row.status){
    					if(row.status==1){
    						return "完全开放";
    					}else{
    						return "不完全开放";
    					}
    					
    				} else {
    					return value;
    				}
    			}
    		},
    		{field:'qfrom',title:'题目来源', width:60},
    		{field:'skey',title:'标准答案', width:60},
    		{field:'content',title:'题干内容', width:100},
    		{field:'key_desc',title:'试题解析', width:100},
    		{field:'create_date',title:'创建时间', width:70},
    		{field:'remark',title:'备注', width:100},
    	]]
    });
    
    var pager = $('#dg').datagrid('getPager');//获得表格的页对象
    pager.pagination({//给页对象设置按钮组
        buttons:[{
            iconCls:'icon-add',
            handler:function(){
            	$('#add').dialog('open');//打开添加对话框
            }
        },{
            iconCls:'icon-search',
            handler:function(){
            	$('#search').dialog('open');//打开查询对话框
            }
        },{
            iconCls:'icon-edit',
            handler:function(){
            	loadRemote();//打开修改对话框
            }
        },{
            iconCls:'icon-remove',
            handler:function(){
            	removeConfirm();//打开删除对话框
            }
        }]
    }); 
});


//填空题，空格计数器
var TOTAL_BLANKS = 0;

$(function(){
	//实例化编辑器
	var ClientID1 = "add_content";
    var ClientID2 = "add_key_desc";
      
    UE.getEditor(ClientID2);
    UE.getEditor(ClientID1);  
    
	//捕获题型选择事件
	$("#qtype").combobox({onChange: function(){
		var qtype = $(this).val();
		//清空当前的选项
		$("#key_setting").empty();
		$("#btn_xuan_addrow").hide();
		
		TOTAL_BLANKS = 0;
		
		//选择题
		if(1==qtype || 2==qtype){
			xuan_init(qtype);
		}else if(3==qtype){
			tiankong();
		}else if(4==qtype){
			panduan();
		}else if(5==qtype){
			wenda();
		}
		
	}});
	
});

//选择题初始化4个选项
xuan_init = function(qtype){
	$("#btn_xuan_addrow").show();
	var options = ['A','B','C','D'];
	$("#key_setting").append('<table class="stable" width="700" align="left" id="key_setting_table">');
	$(options).each(function(i){
		var html = '<tr>';
		html += '<td>选项' + this + '</td>';
		if(1==qtype){
			html += '<td><input type="radio" class="validate[required]" name="skey" value="'+this+'" /></td>';
		}else if(2==qtype){
			html += '<td><input type="checkbox" class="validate[required,minCheckbox[4]]" name="skey" value="'+this+'" /></td>';
		}
		
		var aremove = '<a href="javascript:;" onclick="$(this).parent().parent().remove()" class="easyui-linkbutton" data-options="iconCls:\'icon-remove\'">移除</a>';
		html += '<td><textarea rows="2" cols="40" name="soption" class="validate[required]" id="toption_' + this + '"></textarea></td>';
              html += '<td>额外答案：</td><td><textarea rows="2" cols="5" name="sextend" id="textend_' + this + '"></textarea></td><td> '+aremove+'</td>';
		html += '</tr>';
		
		$(html).appendTo('#key_setting_table').find(".easyui-linkbutton").linkbutton(); 
	}); 
	$("#key_setting").append('</table>');
}


//修改时_选择题初始化选项
xuan_init_load = function(qtype){
	$("#btn_xuan_addrow").hide();
	$("#key_setting").append('<table class="stable" width="700" align="left" id="key_setting_table">');
	$(OPTION_LIST).each(function(i){
		var html = '<tr>';
		html += '<td>选项' + this.SALISA + '</td>';
		if(1==qtype){
			html += '<td><input type="radio" class="validate[required]" name="skey" value="'+this.SALISA+'" /></td>';
		}else if(2==qtype){
			html += '<td><input type="checkbox" class="validate[required,minCheckbox[4]]" name="skey" value="'+this.SALISA+'" /></td>';
		}
		
		var aremove = '<a href="javascript:;" onclick="$(this).parent().parent().remove()" class="easyui-linkbutton" data-options="iconCls:\'icon-remove\'">移除</a>';
		html += '<td><textarea rows="2" cols="40" name="soption" class="validate[required]" id="toption_' + this.SALISA + '">'+this.SOPTION+'</textarea></td>';
		html += '<td>额外答案：</td><td><textarea rows="2" cols="5" name="sextend" id="textend_' + this.SALISA + '">'+this.SEXTEND+'</textarea></td><td> '+aremove+'</td>';
              html += '</tr>';
		
		$(html).appendTo('#key_setting_table').find(".easyui-linkbutton").linkbutton(); 
	}); 
	$("#key_setting").append('</table>');
}


//选择题增加选项
xuan_addrow = function(qtype){
	$("#btn_xuan_addrow").show();
	var options = ['A','B','C','D','E','F','G','H'];
	for(var i=0;i<options.length;i=i+1){
		var this_value = options[i];
		if(!document.getElementById("toption_"+this_value)){
			var html = '<tr>';
			html += '<td>选项' + this_value + '</td>';
			if(1==qtype){
				html += '<td><input type="radio" class="validate[required]" name="skey" value="'+this_value+'" /></td>';
			}else if(2==qtype){
				html += '<td><input type="checkbox" class="validate[required,minCheckbox[4]]" name="skey" value="'+this_value+'" /></td>';
			}
			var aremove = '<a href="javascript::void(0);" onclick="$(this).parent().parent().remove()" class="easyui-linkbutton" data-options="iconCls:\'icon-remove\'">移除</a>';
			html += '<td><textarea rows="2" cols="40" name="soption" class="validate[required]" id="toption_' + this_value + '"></textarea></td>';
                      html += '<td>额外答案：</td><td><textarea rows="2" cols="5" name="sextend" id="textend_' + this_value + '"></textarea></td><td> '+aremove+'</td>';
			html += '</tr>';
			$(html).appendTo('#key_setting_table').find(".easyui-linkbutton").linkbutton(); 
			break;
		}
	};
	
	
}


//判断题
panduan = function(){
	var html = '<table class="stable" width="455" align="left">';
	html += '<tr>';
	html += '<td><b>正确</b> <input type="radio" class="validate[required]" name="skey" value="YES" /> &nbsp;  &nbsp; ';
	html += '<b>错误</b> <input type="radio" class="validate[required]" name="skey" value="NO" /></td>';
	html += '<td>&nbsp;</td><td>&nbsp;</td>';
	html += '</tr></table>';
	$("#key_setting").html(html);
}


//填空题
tiankong = function(){
	var html = '<table class="stable" width="455" align="left">';
	html += '<tr>';
	html += '<td id="TD_BLANKS"></td>';
	html += '</tr>';
	
	html += '<tr>';
	html += '<td><a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:\'icon-add\'" onclick="add_Blank();">增加填空</a> <input type="checkbox" value="yes" name="qcomplex" />混杂模式批改</td>';
	html += '</tr>';
	html += '</table>';
	$(html).appendTo('#key_setting').find(".easyui-linkbutton").linkbutton(); 
}


//问答题
wenda = function(){
	var html = '';
	html += '<textarea name="skey" rows="5" cols="55" style="width:450px"></textarea>';
	$("#key_setting").append(html);
}


//重建答案设置区域
rebuild_key_setting = function(qtype){
	//清空当前的选项
	$("#key_setting").empty();
	$("#btn_xuan_addrow").hide();
	
	var _skey_ = $("#_skey_").val();
	
	if(1==qtype || 2==qtype){//选择题
		xuan_init_load(qtype);
		$("input[name=skey]").val(_skey_.split(''));
	
	}else if(3==qtype){//填空题
		tiankong();
		load_Blank();
	
	}else if(4==qtype){//判断题
		panduan();
		$("input[name=skey]").val([""+_skey_+""]);
		
	}else if(5==qtype){//问答题
		wenda();
		$("textarea[name=skey]").val(unescape(_skey_));
	}
	
}


/********** 工具函数 ***********/

add_Blank = function(){
	
	TOTAL_BLANKS++;
	var ClientID = "add_content";
	content=""+UE.getEditor(ClientID).getContent();
	//判断是否存在即将要插入的BLANK
	var index_of_new_blank = content.indexOf("[BlankArea"+TOTAL_BLANKS+"]");
	while(index_of_new_blank>-1){
		TOTAL_BLANKS++;
		index_of_new_blank = content.indexOf("[BlankArea"+TOTAL_BLANKS+"]");
	}
	
	$("#TD_BLANKS").append('<span>'+TOTAL_BLANKS+'：<input name="skey'+TOTAL_BLANKS+'" type="input" maxlength="30" class="txt" /><a href="javascript:void(0);" mid="'+TOTAL_BLANKS+'">r</a></span>');
	UE.getEditor(ClientID).setContent("[BlankArea"+TOTAL_BLANKS+"]",true);
	
	$("#TD_BLANKS span a").click(function(){
		content=""+UE.getEditor(ClientID).getContent();
		$(this).parent().remove();
		var mid = $(this).attr("mid");
		content = content.replace("[BlankArea"+mid+"]","");
		UE.getEditor(ClientID).setContent(content);
	});
	
}


//加载空格
load_Blank = function(){
	var ClientID = "edit_content";
	
	$(BLANKS).each(function(i){
		if(this.ID != null && this.ID != ""){
			$("#TD_BLANKS").append('<span>'+this.ID+'：<input name="skey'+this.ID+'" value="'+this.VAL+'" type="input" maxlength="30" class="txt" /><a href="javascript:;" mid="'+this.ID+'">r</a></span>');
		}else if(this.QCOMPLEX != null && this.QCOMPLEX == "YES"){
			$("input[name='qcomplex']").attr("checked","checked");
		}
	});
	
	$("#TD_BLANKS span a").click(function(){
		$(this).parent().remove();
		var mid = $(this).attr("mid");
		var content=""+UE.getEditor(ClientID).getContent();
		content = content.replace("[BlankArea"+mid+"]","");
		UE.getEditor(ClientID).setContent(content,true);
	});
		
}


//查看试题详情
function viewQuestion(obj,qid){
	if(obj==null | ""==obj){
		obj = "question_detail";
	}
	$("#"+obj).html("Loading...."+qid);
	$.getJSON("ajax.do?action=getQuestionInfoById", {id:qid,t:rnd()}, function(data){
		var qtype = data.datalist.QTYPE;
		var html = '';
		html += '<div><b>题干：</b>' + data.datalist.CONTENT + '</div>';
		if(qtype=="1" || qtype=="2"){//选择
			html += '<div><b>选项：</b></div>';
			$(data.datalist.OPTIONS).each(function(){
				html += this.SALISA + '：' + this.SOPTION + '<br/>';
			});
			html += '<div><b>答案：</b>' + data.datalist.SKEY + '</div>';
		
		}else if(qtype=="3"){//判断
			html += '<div><b>答案：</b>' + ((data.datalist.SKEY=="YES")?"正确":"错误") + '</div>';
		
		}else if(qtype=="4"){//填空 
			html += '<div><b>答案：</b></div>';
			$(eval(data.datalist.SKEY)).each(function(){
				if(this.ID != null && this.ID != ""){
					html += '[BlankArea' + this.ID + ']：' + this.VAL + '<br/>';
				}else if(this.QCOMPLEX != null && this.QCOMPLEX == "YES"){
					//nothing
				}
				
			});
			
		}else if(qtype=="5"){//问答
			html += '<div><b>答案：</b>' + data.datalist.SKEY + '</div>';
			
		}
		
		html += '';
		$("#"+obj).html(html);
		
	});
	
}